import React, { useState } from 'react';
import { Form, Input, Button, Checkbox, Card, message } from 'antd';
import request from 'umi-request';

// import { history } from 'umi';

async function handleLogin(
  body?: any,
  options?: { [key: string]: any },
) {
  return request<any>('/api/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    data: body,
    ...(options || {}),
  });
}

const Login = () => {
  const [loading, setLoading] = useState(false);

  const onFinish = async (values: any) => {
    setLoading(true);
    const success = await handleLogin(values);
    setLoading(false);
    console.log(success)
    if (success.status == 200) {
      message.success('登录成功')
      window.location.href = '/home'; // 重定向到首页
      localStorage.setItem('isLogin', 'logined')
    }
    else {
      message.error(success.msg)
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
      <Card style={{ width: 400 }} title='欢迎使用文档管理系统'>
        <Form
          name="basic"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="账号"
            name="name"
            rules={[{ required: true, message: '请输入账号!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', }}>
            <Button type="primary" htmlType="submit" loading={loading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
